#include "Segmentator.h"

#include "Utility.h"
#include "Config.h"
#include "IndexGenerator.h"

#include <stdio.h>
#include <math.h>

void createSegment(char* sourceRelation, int segmentNumber, int maxSegmentLenght, bool printText)
{
    FILE* binFileIn = 
        fopen(getFileNameByRelationNameWithExtension(sourceRelation,"bin"),"rb");

    char* segmentName = getSegmentName(sourceRelation, segmentNumber);

    FILE* binFileOut = 
        fopen(getFileNameByRelationNameWithExtension(segmentName,"bin"),"wb");

    fseek(binFileIn,segmentNumber*maxSegmentLenght*sizeof(int)*ARITY,SEEK_SET);

    FILE* txtFileOut = NULL;
    if (printText)
        txtFileOut = fopen(getFileNameByRelationNameWithExtension(segmentName,"txt"),"w");

    int* t = new int[ARITY];
    int tupleCount = 0;
    bool eof = false;
    while ( tupleCount < maxSegmentLenght)
    {
        fread(t,sizeof(int)*ARITY,1,binFileIn);
        eof = feof(binFileIn);
        if(eof)
        {
            break;
        }

        fwrite(t,sizeof(int)*ARITY,1,binFileOut);

        if (printText)
        {
            for (int i = 0; i < ARITY; i++)
                fprintf(txtFileOut, "%d ", t[i]);
            fprintf(txtFileOut, "\n");
        }   

        tupleCount++;
    }

    delete[] t;

    if (printText)
        fclose(txtFileOut);

    fclose(binFileOut);
    fclose(binFileOut);
    fclose(binFileIn);
}

void  makeSegments(char* R, bool generateIndexFile, bool printText)
{
    int i = 0;
    for (i = 0; i < SEGMENTS_COUNT; i++)
    {
        createSegment(R, i, TUPLES_IN_FULL_SEGMENT, printText);
        if (generateIndexFile) 
        {
            generateIndex(getSegmentName("R", i),TUPLES_IN_FULL_SEGMENT, printText);        
        }
    }
}